package itu.dk.bosk.ex3;

import java.io.*;

public class FileInfo {

    public static void main(String[] args) {
        String key = "";
        try{
            FileInfo f = new FileInfo(args[0]);
            for(String s : args){
                if(key.equals("-type")){
                    f.filterByExtension(s);
                }
                key = s;
            }
            f.printDirInfo();
        }catch(ArrayIndexOutOfBoundsException ex){
            System.out.println("You must specify a directory for this program to work on..");
        }
    }
    
    private File dir;
    private File[] files;

    FileInfo(String dirName) {
        File tempDir = new File(dirName);
        if(tempDir.isDirectory()){
            dir = tempDir;
            this.files = dir.listFiles();
        }else{
            System.out.println("The supplied path was not the path of a directory..");
        }
    }

    public void printDirInfo() {
        //Question a:
        System.out.println("The folder: \"" + dir.getAbsolutePath() + "\" contains " + files.length + " files");
        //Question b:
        long byteSize = 0;
        for(File f : files){
            byteSize += f.length();
        }
        System.out.println("with a total size of: "+byteSize+" byte.");
        //Question c:

    }

    public void filterByExtension(final String extension){
        this.files = dir.listFiles(new FilenameFilter() {
            public boolean accept(File file, String name) {
                try{
                    return name.substring(name.length()-extension.length(),name.length()).equals(extension);
                }catch (StringIndexOutOfBoundsException ex) {
                    //If the string isn't long enough, it does not have the right extension..
                    return false;
                }
            }
        });
    }
}
